//
//  ICChatViewController.m
//  ICome
//
//  Created by ENN on 16/3/10.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICChatViewController.h"
#import "ICChatHearder.h"
#import "ICMembersListController.h"
#import "ICChatViewController+Logic.h"
#import "ICChatViewController+NotificationCenter.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "iComeApiManager.h"

#define countDownStart 10

@interface ICChatViewController ()<ICChatBoxViewControllerDelegate,UITableViewDelegate,UITableViewDataSource,BaseCellDelegate,ChatAdaptBaseCellDelete,DetailInfoDelegate,ICGtasksTableViewCellDelegate,ICPubMenuViewDelegate,ICTransferCustomerViewDelegate,UIGestureRecognizerDelegate,MembersListDelegate,ChatMessageTopViewDelegate>

@property (nonatomic, assign)int countDown;
@property (nonatomic, strong)ICVoiceHud *voiceHud;
@property (nonatomic, strong)NSTimer *countDownTimer;   //倒计时定时器
@property (nonatomic, strong)NSTimer *limitTimer;       //时长限制定时器
@property (nonatomic, strong)NSTimer *timer;            //声音动画定时器
@property (nonatomic, weak)MBProgressHUD *hud;

@property (nonatomic, assign)int countIncrease;
@property (nonatomic, assign)int countShow;
@property (nonatomic, assign)BOOL canNotic; // 键盘问题，调整@通知

@end

@implementation ICChatViewController

#pragma mark - UI

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavBackgroundColor:NE_BACKGROUND_COLOR];
    [self setNavShadowColor:NE_BACKGROUND_COLOR];
    _isOffsetFit = YES;  // 默认满足使滚到底部的条件的
    if (!self.group) {
        self.group = self.parameterDictionary[@"group"];
        NSLog(@"gId: %@", self.group.gId);
    }
    [self removeAVPlayerFlag];
    [self setupUI];
    [self registerCell];
    [self initNotificationCenter];
    [self showTopMessage];
    if (self.searchArr) {  // for search
        [self searchDataSource];
    } else {
        [self loadDataSource]; // 正常的
        [self synchronizeGroupInfo];
    }
    
    [self shareContentMessage];
    
    if ([ICMessageHelper isUserRbtGroup:self.group.gId gType:self.group.gType]) {
        [self.view addSubview:self.pubMenuView];
        [self getMenuItems];
    } else if ([ICMessageHelper isServeRbtGroup:self.group.gId gType:self.group.gType]) {
        [self getCustomers];
    }
    
    [self draftsStatus]; // drafts处理
    
    
    [self setStatusBarBackgroundColor:NE_BACKGROUND_COLOR];
    
    //    NSDictionary *param = @{@"method":@"showNews",
    //                            @"param":@{@"title":@"新闻",
    //                                       @"news":@[@{@"dId":@"drt_10000005",@"dName":@"这是一个新闻频道名称"}]
    //                                       }
    //                            };
    //        if (![ICTools isObjEmpty:param]) {
    //            if ([[iComeApiManager instance].delegate respondsToSelector:@selector(openWebViewNativeMethodsWithParams::)]) {
    //                [[iComeApiManager instance].delegate openWebViewNativeMethodsWithParams:param :^(id result) {
    //                    NSDictionary *args = @{@"success":@true,@"data":result};
    //                }];
    //            }
    //        }else {
    //            NSDictionary *args = @{@"success":@false,
    //                                   @"data":@{@"errno":@"1",@"error":@"失败"}};
    //        }
}

- (void)showTopMessage {
    NSDictionary *param = @{@"gId":self.group.gId};
    [[ICChatNetworkManager sharedInstance] getTopMessageWithParam:param Success:^(id object) {
        NSDictionary *dict = object[@"data"];
        if (![ICTools isObjEmpty:dict]) {
            self.topMessageView.hidden = NO;
            NSDictionary *keyDict = [dict[@"key"] jsonValueDecoded];
            NSString *title = @"";
            if (keyDict[@"summary"]) {
                title = keyDict[@"summary"];
            }
            CGSize  size = [title sizeWithMaxWidth:self.view.width - (15*2+10*2) andFont:[UIFont systemFontOfSize:16]];
            NSInteger height = size.height + 105;
            self.topMessageView.titleLabel.text = title;
            self.topMessageView.data = keyDict;
                    
            self.topMessageView.height = height;
            
        } else {
            self.topMessageView.height = 0;
            self.topMessageView.hidden = YES;
        }
        [self setupUI];
    } failure:^(NSError *error) {
        NSLog(@"%@", error.domain);
    }];
}

//- (void)showTopMessage {
//
//    NSString *key = [NSString stringWithFormat:@"TOPMSG_%@_%@",[ICUser currentUser].eId,self.group.gId];
//    NSString *value = [[NSUserDefaults standardUserDefaults] objectForKey:key];
//    if(![ICTools stringEmpty:value]) {
//
//        NSDictionary *dict = [NSDictionary initWithJsonString:value];
//        NSLog(@"解析 %@ ", dict);
//        if ([dict[@"to"] isEqualToString:self.group.gId]) {
//            //            NSInteger time = [[dict objectForKey:@"st"] integerValue];
//            //            NSDate *msgDate = [NSDate dateWithTimeIntervalSince1970:time/1000];
//            NSDate *currentDate = [NSDate date];
//
//            NSDate *endDate = [NSDate getDateFromString:[dict objectForKey:@"expire"]];
//
//            if ([currentDate earlierDate:endDate]) {
//                self.topMessageView.hidden = NO;
//
//                NSDictionary *keyDict = [dict[@"key"] mj_JSONObject];
//                NSString *title = keyDict[@"title"];
//                CGSize  size = [title sizeWithMaxWidth:self.view.width - 20 andFont:[UIFont systemFontOfSize:16]];
//                if (size.height <= 48) {
//                    self.topMessageView.height = 48;
//                } else {
//                    self.topMessageView.height = size.height + 10;
//                }
//                self.topMessageView.titleLabel.text = title;
//
//                self.topMessageView.url = keyDict[@"url"];
//            } else {
//                self.topMessageView.height = 0;
//                self.topMessageView.hidden = YES;
//            }
//        }
//    }
//    [self setupUI];
//}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    _isGroupValid = [ICMessageDatabase isValidWithGroup:self.group.gId];
    if (_isGroupValid) {
        [self setupNav];
    } else { // 组无效了
        [self invalidState];
    }
    _isKeyBoardAppear = NO;   // 默认键盘是在下面的
    [self setChatTitle];
    
    if (self.textView == nil) {
        self.textView = self.chatBoxVC.chatBox.textView;
    }
    self.canNotic = YES;
}

- (void)setChatTitle {
    
    UIView *titleView = [[UIView alloc] init];
    titleView.frame = CGRectMake(0, 0, 220, 44);
    
    //    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 220, 44)];
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.font = ICBOLDFont(18);
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    
    NSString *groupName = [ICMessageDatabase getGroupName:self.group.gId];
    if (groupName.length > 13) {
        groupName = [groupName stringByReplacingOccurrencesOfString:[groupName substringWithRange:NSMakeRange(13, groupName.length - 13)] withString:@"..."];
    }
    titleLabel.text = groupName;
    [titleView addSubview:titleLabel];
    
    [titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(titleView.mas_centerX);
        make.centerY.equalTo(titleView.mas_centerY);
    }];
    
    
    if ([self.group.gType isEqualToString:@"2"]) {
        UILabel *countLabel = [[UILabel alloc] init];
        countLabel.font = ICBOLDFont(18);
        countLabel.textColor = [UIColor whiteColor];
        countLabel.textAlignment = NSTextAlignmentCenter;
        [titleView addSubview:countLabel];
        NSInteger count = [ICMessageDatabase getGroupUserCount:self.group.gId];
        NSLog(@"%ld", count);
        countLabel.text = [NSString stringWithFormat:@"(%ld)", count];
        [countLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(titleLabel.mas_centerY);
            make.left.equalTo(titleLabel.mas_right);
        }];
    }
    
    self.navigationItem.titleView = titleView;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [ICMessageDatabase updateGroupUnreadMessageCountWithGroupId:self.group.gId count:0]; // 清除未读数
    [ICMessageDatabase updateGroupAlertStatus:0 gId:self.group.gId];
    [ICMessageHelper updateGroupReadWithGroupId:self.group.gId];
    
    if (self.textView.text.length > 0 && ![self.textView.text isTrimmingSpace]) {
        [ICMessageDatabase saveDrafts:self.group.gId draft:self.textView.text];
    } else {
        [ICMessageDatabase deleteDrafts:self.group.gId];
    }
    if(self.dataSource.count > 0){
        ICMessageFrame *lastMessageF = [self.dataSource lastObject];
        ICMessage *message = lastMessageF.model.message;
        // 正常保存最后一条消息到 消息组表中
        if([self.group.lastMsgId intValue] <= [message.messageId intValue]){
            [ICMessageDatabase updateGroupLastMessageTime:message.to lastMsgTime:message.date lastMsgTxt:message.content lastMsgId:message.messageId lastChangeId:message.from];
        }else{
            //删除消息，IM更新最后一条消息 最大消息ID不变
            [ICMessageDatabase updateGroupLastMessageTime:message.to lastMsgTime:message.date lastMsgTxt:message.content lastMsgId:self.group.lastMsgId lastChangeId:message.from];
        }
    }
    [self handleTapGesture:nil];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
#pragma mark - NAV

- (void)setupNav
{
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    if ([ICMessageHelper isServeRbtGroup:self.group.gId gType:self.group.gType]) {
        
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImageName:@"icon_tran_server_blue" itemType:UIBarButtonItemTypeRight target:self action:@selector(transferButtonClicked)];
        
    } else if ([ICMessageHelper isUserRbtGroup:self.group.gId gType:self.group.gType]) {
        //        NSLog(@"还没想好!!!!");
    } else { // 正常群组打开详情
        
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImageName:@"icon_chat_detail_blue" itemType:UIBarButtonItemTypeRight target:self action:@selector(rightBarButtonClicked)];
    }
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImageName:@"App_back_blue" itemType:UIBarButtonItemTypeLeft target:self action:@selector(backClick)];
    
}

- (void)backClick {
    if (![ICTools stringEmpty:self.backFlag]) {
        int index = (int)[[self.navigationController viewControllers] indexOfObject:self];
        int flagIndex =  [self.backFlag intValue];
        if (index >= flagIndex) {
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:(index-flagIndex)] animated:YES];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)rightBarButtonClicked
{
    ICChatDetailViewController *chatDetailVC = [[ICChatDetailViewController alloc] init];
    chatDetailVC.group = self.group;
    chatDetailVC.delegate = self;
    if([self.group.gType integerValue] == ICGroup_GENIUS)
    {
        chatDetailVC.power = NO;
    }
    // 精灵群设置权限 YES 是默认 NO 是没有设置群权利
    [self.navigationController pushViewController:chatDetailVC animated:YES];
}

- (void)transferButtonClicked {
    [self.transCustomerView show];
    [self handleTapGesture:nil];
}

#pragma mark - Tableview data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id obj = self.dataSource[indexPath.row];
    if ([obj isKindOfClass:[NSString class]]) {
        return [[UITableViewCell alloc] init];
    } else {
        ICMessageFrame *modelFrame = (ICMessageFrame *)obj;
        NSString *identifier = modelFrame.model.message.type;
        if ([identifier isEqualToString:TypeSystem]) {
            ICChatSystemCell *cell = [ICChatSystemCell cellWithTableView:tableView reusableId:identifier];
            cell.messageF = modelFrame;
            return cell;
        } else if ([identifier isEqualToString:TypeChance]) {
            ICChnMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:TypeChance forIndexPath:indexPath];
            cell.message = [ICMessageHelper getChnModelModelWith:modelFrame.model.message];
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else if ([identifier isEqualToString:TypeNotif]) {
            ICNotifyMsgCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
            ICNotify *notify = [ICMessageHelper getNotifyModelModelWith:modelFrame.model.message];
            cell.message = notify;
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else if ([identifier isEqualToString:TypePending]) {
            ICGtasksTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TypePending forIndexPath:indexPath];
            cell.model = [ICMessageHelper getGtasksModelWith:modelFrame.model.message];
            cell.delegate = self;
            cell.dateLabel.hidden = YES;
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else if ([identifier compare:@"999" options:NSNumericSearch] != NSOrderedAscending) {
            
            ICChatAdaptBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[ICChatAdaptBaseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.longPressDelegate = self;
            NSString *nName = [ICMessageDatabase nickNameWithEid:modelFrame.model.message.from
                                                             gId:modelFrame.model.message.to];
            [self setCell:cell rowAtIndexPath:indexPath nName:nName];
            return cell;
        }
        ICChatMessageBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[ICChatMessageBaseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.longPressDelegate = self;
        cell.modelFrame = modelFrame;
        return cell;
    }
}

- (void)setCell:(ICChatAdaptBaseCell *)cell rowAtIndexPath:(NSIndexPath *)indexPath nName:(NSString *)nName{
    ICMessageFrame *modelFrame = self.dataSource[indexPath.row];
    // set 数据
    cell.data = @{@"type":modelFrame.model.message.type,
                  @"txt":modelFrame.model.message.content,
                  @"fr":modelFrame.model.message.from,
                  @"to":self.group.gId,
                  @"data":modelFrame.model.message.fileKey,
                  @"nName":nName
                  };
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICMessageFrame *messageF = [self.dataSource objectAtIndex:indexPath.row];
    NSString *identifier = messageF.model.message.type;
    
    if ([identifier compare:@"999" options:NSNumericSearch] != NSOrderedAscending) {
        return [tableView fd_heightForCellWithIdentifier:identifier cacheByIndexPath:indexPath configuration:^(ICChatAdaptBaseCell *cell) {
            [self setCell:cell rowAtIndexPath:indexPath nName:@""];
        }];
    }
    return messageF.cellHight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self handleTapGesture:nil];
    ICMessageFrame *modelFrame = [self.dataSource objectAtIndex:indexPath.row];
    NSString *identifier = modelFrame.model.message.type;
    NSString *link = modelFrame.model.message.lnk;
    if (![ICTools stringEmpty:link]) {
        if ([identifier isEqualToString:TypeNotif] || [identifier isEqualToString:TypeChance]) {
            [self pushCustomViewControllerURL:link fromViewController:self animated:YES];
        }
    }
    // 用于外部自定义消息体
    if ([identifier compare:@"999" options:NSNumericSearch] != NSOrderedAscending) {
        if ([[iComeApiManager instance].delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:select:)]) {
            NSDictionary  *data = @{@"type":modelFrame.model.message.type,
                                    @"txt":modelFrame.model.message.content,
                                    @"fr":modelFrame.model.message.from,
                                    @"to":self.group.gId,
                                    @"data":modelFrame.model.message.fileKey,
                                    @"nName":@""
                                    };
            [[iComeApiManager instance].delegate tableView:tableView didSelectRowAtIndexPath:indexPath select:data];
            
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self handleTapGesture:nil];
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath {
    if ([cell isKindOfClass:[ICChatMessageVideoCell class]] && self) {
        ICChatMessageVideoCell *videoCell = (ICChatMessageVideoCell *)cell;
        [videoCell stopVideo];
    }
}

#pragma mark - ICChatBoxViewControllerDelegate

//通知@谁
-(void)noticewho
{
    if(([self.group.gType integerValue] == ICGroup_GENIUS || [self.group.gType integerValue] == ICGroup_MULTI) && self.canNotic)
    {
        self.canNotic = NO;
        /** @成员列表*/
        ICMembersListController *membersListController = [[ICMembersListController alloc] init];
        membersListController.gId = self.group.gId;
        membersListController.delegate = self;
        [self.navigationController pushViewController:membersListController animated:YES];
    }
}

- (void)chatBoxViewController:(ICChatBoxViewController *)chatboxViewController
       didChangeChatBoxHeight:(CGFloat)height
{
    NSLog(@"ICChatBoxViewController.view : %f", height);
    [self setStatusBarBackgroundColor:NE_BACKGROUND_COLOR];
    //    self.chatBoxVC.view.top = self.view.bottom-height-[ICTools getNavbarHeight]-[ICTools getStatusbarHeight];
    self.chatBoxVC.view.top = APP_Frame_Height - height-[ICTools getNavbarHeight]-[ICTools getStatusbarHeight];
    //    self.chatBoxVC.view.top = self.view.bottom - height-[ICTools getNavbarHeight]-[ICTools getStatusbarHeight];
    self.tableView.height = self.chatBoxVC.view.top - self.topMessageView.height;
    
    if (height == [ICTools getChatBoxInputHeight]) {
        [self.tableView reloadData];
        _isKeyBoardAppear  = NO;
    } else {
        [self scrollToBottomAnimated:YES];
        _isKeyBoardAppear  = YES;
    }
    
    if (self.textView == nil) {
        self.textView = chatboxViewController.chatBox.textView;
    }
}
// send text message
- (void)chatBoxViewController:(ICChatBoxViewController *)chatboxViewController
              sendTextMessage:(NSString *)messageStr
{
    
    if (messageStr && messageStr.length > 0) {
        if(self.Mutabledict !=nil && self.Mutabledict.allKeys.count > 0){
            [self matching:messageStr];
            [self sendATTextMessageWithContent:messageStr];
            self.Mutabledict = nil;
        }else{
            [self sendTextMessageWithContent:messageStr];
        }
    }
}

- (void) chatBoxViewController:(ICChatBoxViewController *)chatboxViewController showPubMenu:(BOOL)show {
    if (show) {
        if (self.pubMenuView) {
            [self.pubMenuView showPubMenu];
        }
    }
}

// send image message
- (void)chatBoxViewController:(ICChatBoxViewController *)chatboxViewController
             sendImageMessage:(UIImage *)image
                    imagePath:(NSString *)imgPath
{
    if (image && imgPath) {
        [self sendImageMessageWithImgPath:imgPath];
    }
}

// send Zoomvideo
- (void) chatBoxViewController:(ICChatBoxViewController *)chatboxViewController sendZoomvideoMessage:(NSString *)message
{
    [self sendZoomVideoMessage:message];
}

// send voice message 音频
- (void)chatBoxViewController:(ICChatBoxViewController *)chatboxViewController sendVoiceMessage:(NSString *)voicePath
{
    [self timerInvalue]; // 销毁定时器
    self.voiceHud.hidden = YES;
    
    if (voicePath) {
        NSString *path = [self mediaPath:voicePath];
        NSString *lnk = [NSString stringWithFormat:@"%ld",(unsigned long)[[ICRecordManager shareManager] durationWithVideo:[NSURL fileURLWithPath:path]]];
        
        
        if ([lnk intValue] > 0) { //语音时长至少为1
            [self sendVoiceMessage:lnk voicePath:voicePath];
            
        }else {
            [self voiceRecordSoShort];
        }
    }
}

- (void)chatBoxViewController:(ICChatBoxViewController *)chatboxViewController didVideoViewAppeared:(ICVideoView *)videoView
{
    [_chatBoxVC.view setFrame:CGRectMake(0, APP_Frame_Height-[ICTools getChatBoxInputHeight], App_Frame_Width, APP_Frame_Height)];
    videoView.hidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        self.tableView.height = APP_Frame_Height - [ICTools getRecordeVideoViewHeight] - [ICTools getNavbarHeight]-[ICTools getStatusbarHeight];
        self.chatBoxVC.view.frame = CGRectMake(0, [ICTools getRecordeVideoViewWidth], App_Frame_Width, [ICTools getRecordeVideoViewHeight]);
        [self scrollToBottomAnimated:YES];
    } completion:^(BOOL finished) { // 状态改变
        self.chatBoxVC.chatBox.status = ICChatBoxStatusShowVideo;
        // 在这里创建视频设配
        UIView *videoLayerView = [videoView viewWithTag:1000];
        UIView *placeholderView = [videoView viewWithTag:1001];
        [[ICVideoManager shareManager] setVideoPreviewLayer:videoLayerView];
        [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(videoPreviewLayerWillAppear:)
                                       userInfo:placeholderView
                                        repeats:NO];
    }];
}

- (void)chatBoxViewController:(ICChatBoxViewController *)chatboxViewController sendVideoMessage:(NSString *)videoPath
{
    ICMessageFrame *messageFrame = [ICMessageHelper createMessageFrame:TypeVideo
                                                               content:@"[视频]"
                                                                  path:videoPath
                                                                  from:[ICUser currentUser].eId
                                                                    to:self.group.gId
                                                                   lnk:nil
                                                               fileKey:nil
                                                              isSender:YES
                                              receivedSenderByYourself:NO]; // 创建本地消息
    [self sendVideoImage:messageFrame videoPath:videoPath];
}

// 此处的fileName为：fileKey_fileName.后缀
- (void)chatBoxViewController:(ICChatBoxViewController *)chatboxViewController sendFileMessage:(NSString *)fileName
{
    if (fileName) {
        [self sendFileMessageWithFileName:fileName];
    }
}

// 开始录音前还原声音图片
- (void)chatBoxProcessingBeforeStartRecordingVoice
{
    self.voiceHud.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_voice_1"];
    [self timerInvalue];
    [self cancelSetVoiceHudHidden];
}

- (void)voiceDidCancelRecording
{
    [self timerInvalue];
    self.voiceHud.hidden = YES;
}
- (void)voiceDidStartRecording
{
    [self timerInvalue];
    self.voiceHud.hidden = NO;
    [self timer];
    [self limitTimer];
    [self countDownTimer];
}

// 向外或向里移动
- (void)voiceWillDragout:(BOOL)inside
{
    if (inside) {
        if (self.countDown <= countDownStart) {
            [_timer setFireDate:[NSDate distantFuture]];
            self.voiceHud.countDownLabel.hidden = NO;
            _voiceHud.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_voice_countDown"];
        }else {
            [_timer setFireDate:[NSDate distantPast]];
            self.voiceHud.countDownLabel.hidden = YES;
        }
    } else {
        [_timer setFireDate:[NSDate distantFuture]];
        self.voiceHud.countDownLabel.hidden = YES;
        self.voiceHud.animationImages  = nil;
        self.voiceHud.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_voice_cancel"];
    }
}
- (void)progressChange
{
    AVAudioRecorder *recorder = [[ICRecordManager shareManager] recorder] ;
    [recorder updateMeters];
    float power= [recorder averagePowerForChannel:0];//取得第一个通道的音频，注意音频强度范围时-160到0,声音越大power绝对值越小
    CGFloat progress = (1.0/160)*(power + 160);
    self.voiceHud.hidden = NO;
    self.voiceHud.progress = progress;
}

- (void)voiceRecordSoShort
{
    [self timerInvalue];
    self.voiceHud.animationImages = nil;
    self.voiceHud.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_voice_short"];
    [self cancelSetVoiceHudHidden];
    [self performSelector:@selector(setVoiceHudHidden) withObject:nil afterDelay:0.5f];
}

- (void)cancelSetVoiceHudHidden {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setVoiceHudHidden) object:nil];
}

- (void)setVoiceHudHidden {
    self.voiceHud.hidden = YES;
}

#pragma mark - Private Method

// 增加数据源并刷新
- (void)addObject:(ICMessageFrame *)messageF
         isSender:(BOOL)isSender
{
    ICMessageFrame *lastF = [self.dataSource lastObject];
    NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:lastF.model.message.date/1000];
    NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:messageF.model.message.date/1000];
    BOOL isSame = [NSDate isSameDay:date1 date2:date2];
    if (!isSame) {
        NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
        [dateFormater setDateFormat:@"yyyy-MM-dd"];
        NSString *datestr = [dateFormater stringFromDate:date2];
        ICMessageFrame *timeF = [ICMessageHelper createTimeMessageFrame:TypeSystem
                                                                content:datestr
                                                                   path:nil
                                                                   from:nil
                                                                     to:self.group.gId
                                                                fileKey:nil
                                                               isSender:NO
                                               receivedSenderByYourself:NO];
        [self.dataSource addObject:timeF];
    }
    [self.dataSource addObject:messageF];
    [self.tableView reloadData];
    if (isSender || _isKeyBoardAppear || _isOffsetFit) { // 是发送者或者键盘弹出来或者满足偏移量小于300的情况才滚动到底部
        [self scrollToBottomAnimated:YES];
    }
}

- (void)searchDataSource
{
    self.dataSource = self.searchArr;
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:self.indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
    
}

- (void)setupUI
{
    // 注意添加顺序
    [self addChildViewController:self.chatBoxVC];
    [self.view addSubview:self.chatBoxVC.view];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.topMessageView];
    
    self.tableView.backgroundColor = BACKGROUNDCOLOR;
    NSLog(@"topMessageView 高度 %f", self.topMessageView.height);
    self.tableView.frame = CGRectMake(0, self.topMessageView.height, self.view.width, APP_Frame_Height-[ICTools getChatBoxInputHeight]-[ICTools getNavbarHeight]-[ICTools getStatusbarHeight]-self.topMessageView.height);
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [ICMessageDatabase updateGroupUnreadMessageCountWithGroupId:self.group.gId count:0]; // 清除未读数
}

- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

// register Cells
- (void)registerCell
{
    [self.tableView registerClass:[ICChatMessageTextCell class] forCellReuseIdentifier:TypeText];
    [self.tableView registerClass:[ICChatMessageImageCell class] forCellReuseIdentifier:TypePic];
    [self.tableView registerClass:[ICChatMessageVideoCell class] forCellReuseIdentifier:TypeVideo];
    [self.tableView registerClass:[ICChatMessageVoiceCell class] forCellReuseIdentifier:TypeVoice];
    [self.tableView registerClass:[ICChatMessageFileCell class] forCellReuseIdentifier:TypeFile];
    [self.tableView registerClass:[ICChatMessageShareCell class] forCellReuseIdentifier:TypePicText];
    [self.tableView registerClass:[ICChatMessageRedPacketCell class] forCellReuseIdentifier:TypeRedPacket];
    [self.tableView registerClass:[ICChatMessageATTextCell class] forCellReuseIdentifier:TypeAtText];
    [self.tableView registerClass:[ICChatMessageConferenceCell class] forCellReuseIdentifier:TypeVideoConference];
    [self.tableView registerClass:[ICMessageDrtNewsCell class] forCellReuseIdentifier:TypeDrtNews];
    [self.tableView registerClass:[ICChatMessageURLTextCell class] forCellReuseIdentifier:TypeTextURL];
    [self.tableView registerClass:[ICChatMessageReminderCell class] forCellReuseIdentifier:TypeQuestion];
    
    [self.tableView registerClass:[ICNotifyMsgCell class] forCellReuseIdentifier:TypeNotif];
    [self.tableView registerClass:[ICChnMessageCell class] forCellReuseIdentifier:TypeChance];
    [self.tableView registerClass:[ICGtasksTableViewCell class] forCellReuseIdentifier:TypePending];
    [self.tableView registerClass:[ICChatSystemTopCell class] forCellReuseIdentifier:TypeSysTop];
    
    // 用于动态注册
    NSArray *cellClassList =[[NSUserDefaults standardUserDefaults] valueForKey:@"cellClassList"];
    
    for (NSDictionary *dict in cellClassList) {
        NSString *class = dict[@"class"];
        NSString *identifier = dict[@"id"];
        if (![ICTools stringEmpty:class] && ![ICTools stringEmpty:identifier]) {
            [self.tableView registerClass:NSClassFromString(class) forCellReuseIdentifier:identifier];
        }
    }
}


- (void)statusChanged:(ICMessageFrame *)messageF
{
    [self.dataSource removeObject:messageF];
    // 保证消息id都存在，改变消息状态
    [ICMessageDatabase changeMessageStatus:messageF.model.message status:ICMessageStatus_back];
    // 删除消息附件
    [ICMessageHelper deleteMessage:messageF.model];
    [self.tableView beginUpdates];
    [self.tableView deleteRowAtIndexPath:_longIndexPath withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
}

// 这个方法别忘了否则menu菜单出不来(本身成为第一响应者，能接收事件响应)
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

#pragma mark - Notification

// 文件路径
- (NSString *)mediaPath:(NSString *)originPath
{
    // 这里文件路径重新给，根据文件名字来拼接
    NSString *name = [[originPath lastPathComponent] stringByDeletingPathExtension];
    return [[ICRecordManager shareManager] receiveVoicePathWithFileKey:name];
}

- (void)timerInvalue {
    // 动画定时器
    if (_timer.isValid) {
        [_timer invalidate];
        _timer  = nil;
    }
    // 时长限制定时器
    if (_limitTimer.isValid) {
        [_limitTimer invalidate];
        _limitTimer = nil;
    }
    // 倒计时定时器
    if (_countDownTimer.isValid) {
        [_countDownTimer invalidate];
        _countDownTimer = nil;
    }
}

// 有draft时的处理
- (void)draftsStatus
{
    NSString *draft = [ICMessageDatabase getDrafts:self.group.gId];
    if (draft) {
        self.chatBoxVC.chatBox.textView.text = draft;
        [self thematching:draft];
        //        [self.chatBoxVC.chatBox.textView becomeFirstResponder];
    }
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    // contentSize的高度减去当前屏幕的高度再减去tableView的当前偏移量,得到结果如果大于300则收到消息不用滚动到底部，否则滚动到底部;300是我大约估算的结果，3个文本的cell的偏移量大约是272，如果有视频或图片的时候会大一些所以我取300，比微信的稍微大了一点；
    CGFloat offset =  self.tableView.contentSize.height-(self.tableView.height+self.tableView.contentOffset.y);
    if (offset < 300) {
        _isOffsetFit   = YES;
    } else {
        _isOffsetFit   = NO;
    }
}


- (void)handleTapGesture:(UITapGestureRecognizer *)recognizer
{
    [self.chatBoxVC resignFirstResponder];
    if (_pubMenuView) {
        [self.pubMenuView hiddenItemTable];
    }
}

- (void)scrollToBottomAnimated:(BOOL)animated
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.dataSource.count > 0 && self.dataSource != nil) {
            [self.tableView scrollToRow:self.dataSource.count-1 inSection:0 atScrollPosition:UITableViewScrollPositionBottom animated:animated];
        }
    });
}

// 移除录视频时的占位图片
- (void)videoPreviewLayerWillAppear:(NSTimer *)timer
{
    UIView *placeholderView = (UIView *)[timer userInfo];
    [placeholderView removeFromSuperview];
}

- (void)reloadTableView
{
    [self.tableView reloadData];
}

- (void)reloadSpecialCell:(ICMessageFrame *)messageF
{
    for (int i = 0; i < self.dataSource.count; i ++) {
        id obj = self.dataSource[i];
        if ([obj isKindOfClass:[ICMessageFrame class]]) {
            ICMessageFrame *mf = (ICMessageFrame *)obj;
            if ([messageF.model.message.messageId isEqualToString:mf.model.message.messageId]) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                break;
            }
        }
    }
}


#pragma mark - public method

// 路由响应
- (void)routerEventWithName:(NSString *)eventName
                   userInfo:(NSDictionary *)userInfo
{
    ICMessageFrame *modelFrame = [userInfo objectForKey:MessageKey];
    if ([eventName isEqualToString:GXRouterEventTextUrlTapEventName]) {
        
    } else if ([eventName isEqualToString:GXRouterEventImageTapEventName]) {
        NSString *imgPath = modelFrame.model.mediaPath;
        NSString *orgImgPath = [[ICMediaManager sharedManager] originImgPath:modelFrame];
        if ([ICFileTool fileExistsAtPath:orgImgPath]) {
            modelFrame.model.mediaPath = orgImgPath;
            imgPath = orgImgPath;
        }
        [self showLargeImageWithOglImage:[userInfo objectForKey:@"oglImage"]
                                WithPath:imgPath
                            withMessageF:modelFrame
                                fromView:[userInfo objectForKey:@"obj"]
                             currentCell:[userInfo objectForKey:@"currentCell"]];
        
    } else if ([eventName isEqualToString:GXRouterEventVoiceTapEventName]) {
        // 语音
        UIImageView *imageView = (UIImageView *)userInfo[VoiceIcon];
        UIView *redView        = (UIView *)userInfo[RedView];
        [self chatVoiceTaped:modelFrame voiceIcon:imageView redView:redView];
    } else if ([eventName isEqualToString:GXRouterEventVideoTapEventName]) {
        [self showLargeVideoWithOglImage:[userInfo objectForKey:@"oglImage"] fromView:[userInfo objectForKey:@"obj"] currentCell:[userInfo objectForKey:@"currentCell"]];
    } else if ([eventName isEqualToString:GXRouterEventShareTapEvent]) {
        // 图片链接点击
        [self pushCustomViewControllerURL:modelFrame.model.message.lnk
                       fromViewController:self
                                 animated:YES];
    } else if ([eventName isEqualToString:GXRouterEventURLSkip]) {
        
        [self pushCustomViewControllerURL:[userInfo objectForKey:@"url"]
                       fromViewController:self
                                 animated:YES];
        
    } else if ([eventName isEqualToString:GXRouterEventScanFile]) {
        NSString *filePath = [userInfo objectForKey:@"filePath"];
        if ([[[NSDictionary dictionaryWithJsonString:modelFrame.model.message.lnk] objectForKey:@"x"] intValue] == ICFileType_Video){
            UIButton *btn = (UIButton *)[userInfo objectForKey:@"fileBtn"];
            
            NSMutableArray *items = [[NSMutableArray alloc] init];
            ICAVPlayerGroupItem *item = [ICAVPlayerGroupItem new];
            item.thumbView = btn;
            item.videoPath = filePath;
            [items addObject:item];
            
            ICAVPlayer *player = [[ICAVPlayer alloc] initWithGroupItems:items];
            [player presentFromVideoView:btn toContainer:App_RootCtr.view animated:YES completion:nil];
        } else {
            NSString *lnk = modelFrame.model.message.lnk;
            NSDictionary *dicLnk = [NSDictionary dictionaryWithJsonString:lnk];
            NSString *name  = [dicLnk objectForKey:@"n"];
            ICFileScanController *scanVC = [[ICFileScanController alloc] init];
            scanVC.filePath              = filePath;
            scanVC.orgName               = name;
            [self.navigationController pushViewController:scanVC animated:YES];
        }
    }else if ([eventName isEqualToString:GXRouterEventRedPacketTapEvent]) {
        [self clickRedPacketTaped:modelFrame.model];
    }else if([eventName isEqualToString:GXRouterEventsingleFingerTwo])
    {
        // 发送@消息的前提
        if([self.group.gType integerValue] == ICGroup_GENIUS || [self.group.gType integerValue] == ICGroup_MULTI)
        {
            [self.textView insertText:@"@"];
            [self chooseMembers:userInfo];
        }
    } else if ([eventName isEqualToString:GXRouterEventQuestionEvent]) {
        // 机器人 发送@消息
        NSString *name = userInfo[@"name"] == nil ? @"":userInfo[@"name"];
        NSString *from = userInfo[@"from"] == nil ? @"":userInfo[@"from"];
        NSString *text = [NSString stringWithFormat:@"@%@\u2005%@", name,userInfo[@"text"]];
        [self.Mutabledict setObject:from forKey:name];
        
        [self sendATTextMessageWithContent:text];
        
    } else if ([eventName isEqualToString:GXRouterEventNoticeMessage]) {
        // 打开  可能是打开某个原生界面
        [self pushCustomViewControllerURL:[userInfo objectForKey:@"url"]
                       fromViewController:self
                                 animated:YES];
        
        if ([userInfo objectForKey:@"messageId"]) {
            // 更新具体某条消息是否已读
            [ICMessageDatabase updateMessageStatus:[userInfo objectForKey:@"messageId"]
                                               gId:self.group.gId
                                            status:ICMessageStatus_read];
        }
        
    } else if ([eventName isEqualToString:GXRouterEventDrtNewsTapEvent]) {
        ICMessageFrame *newsModelFrame = [userInfo objectForKey:TypeDrtNews];
        // 打开新闻详情
        NSDictionary *param = @{@"gId":self.group.gId,
                                @"data":newsModelFrame.model.message.fileKey};
        WEAKSELF
        if ([[iComeApiManager instance].delegate respondsToSelector:@selector(openNewsDetailFromViewC::)]) {
            [[iComeApiManager instance].delegate openNewsDetailFromViewC:weakSelf :param];
        }
    } else if ([eventName isEqualToString:GXRouterEventSysTopEvent]) {
        NSString *url = [[NSDictionary dictionaryWithJsonString:modelFrame.model.message.fileKey] objectForKey:@"url"];
        if (url){
            [self pushCustomViewControllerURL:url
                           fromViewController:self
                                     animated:YES];
        }
    }
    
}

#pragma mark - Getter and Setter

- (ICChatBoxViewController *) chatBoxVC
{
    if (!_chatBoxVC) {
        _chatBoxVC = [[ICChatBoxViewController alloc] initWithGroup:self.group];
        [_chatBoxVC.view setFrame:CGRectMake(0,APP_Frame_Height-[ICTools getChatBoxInputHeight]-[ICTools getNavbarHeight]-[ICTools getStatusbarHeight], App_Frame_Width, APP_Frame_Height)];
        _chatBoxVC.delegate = self;
    }
    return _chatBoxVC;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        self.extendedLayoutIncludesOpaqueBars = NO;
        
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}

- (ICVoiceHud *)voiceHud
{
    if (!_voiceHud) {
        _voiceHud = [[ICVoiceHud alloc] initWithFrame:CGRectMake(0, 0, 155, 155)];
        _voiceHud.hidden = YES;
        [self.view addSubview:_voiceHud];
        _voiceHud.center = CGPointMake(App_Frame_Width/2, APP_Frame_Height/2);
    }
    return _voiceHud;
}

- (NSTimer *)timer
{
    if (!_timer) {
        _timer =[NSTimer scheduledTimerWithTimeInterval:0.3f
                                                 target:self
                                               selector:@selector(progressChange)
                                               userInfo:nil
                                                repeats:YES];
    }
    return _timer;
}

- (NSTimer *)limitTimer {
    if (!_limitTimer) {
        _limitTimer = [NSTimer scheduledTimerWithTimeInterval:60.0f
                                                       target:self
                                                     selector:@selector(limitTimerAction)
                                                     userInfo:nil
                                                      repeats:NO];
    }
    return _limitTimer;
}

- (void)limitTimerAction {
    [self.chatBoxVC.chatBox.delegate chatBoxDidStopRecordingVoice:self.chatBoxVC.chatBox];
}

- (NSTimer *)countDownTimer {
    if (!_countDownTimer) {
        self.countIncrease = 0;
        self.countShow = 0;
        _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                           target:self
                                                         selector:@selector(countDownTimerAction)
                                                         userInfo:nil
                                                          repeats:YES];
        
    }
    return _countDownTimer;
}

- (void)countDownTimerAction {
    self.countShow = 60 - self.countIncrease++;
    self.countDown = self.countShow;
    if (self.countShow == countDownStart) {
        self.voiceHud.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_voice_countDown"];
        self.voiceHud.countDownLabel.hidden = NO;
    }
    if (self.countShow <= countDownStart) {
        if (self.countShow < 0) {
            self.countShow = 1;
        }
        [self.timer setFireDate:[NSDate distantFuture]];
        self.voiceHud.countDown = self.countShow;
    }
}

-(ICPubMenuView *)pubMenuView {
    if (!_pubMenuView) {
        _pubMenuView = [[ICPubMenuView alloc] initWithDisplayView:self.view];
        _pubMenuView.frame = CGRectMake(0, APP_Frame_Height-[ICTools getChatBoxInputHeight]-[ICTools getNavbarHeight]-[ICTools getStatusbarHeight], App_Frame_Width, [ICTools getChatBoxInputHeight]);
        _pubMenuView.delegate = self;
    }
    return _pubMenuView;
}

-(ICTransferCustomerView *)transCustomerView {
    if (!_transCustomerView) {
        _transCustomerView = [[ICTransferCustomerView alloc] initWithCustomers:nil superView:self.view];
        _transCustomerView.delegate = self;
        [self.view addSubview:_transCustomerView];
    }
    return _transCustomerView;
}

-(ICChatMessageTopView *)topMessageView {
    if(!_topMessageView){
        _topMessageView = [[ICChatMessageTopView alloc] init];
        _topMessageView.frame = CGRectMake(0, 0, App_Frame_Width, 0);
        _topMessageView.delegate = self;
        _topMessageView.hidden = YES;
        _topMessageView.backgroundColor = [UIColor whiteColor];
    }
    return _topMessageView;
}

#pragma mark - MembersListDelegate

-(NSMutableDictionary *)Mutabledict {
    if(!_Mutabledict){
        _Mutabledict = [[NSMutableDictionary alloc] init];
    }
    return _Mutabledict;
}

- (void)dealloc
{
    [[ICMediaManager sharedManager] clearCaches];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.tableView removeObserver:self forKeyPath:@"contentOffset"];
    if (self.voicePath) { // 录音停止
        [[ICRecordManager shareManager] stopPlayRecorder:self.voicePath];
    }
    [self timerInvalue];
}

@end
